<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active {
      color: red;
    }
  </style>
</head>

<body>
  <div id="app">

    <h3>路由基础</h3>
    <router-link tag="button" to="/home">
      首页
    </router-link>
    <router-link tag="button" to="/news">
      新闻页
    </router-link>
    <router-link tag="button" to="/about">
      关于我们
    </router-link>
    <hr>
    <router-view></router-view>
    <!-- 在视图上 定义 路由组件出口 -->

  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    // 准备三个 路由组件的 options对象
    const Home = {
      template: `
        <div>
          <h2>我是首页</h2>   
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h2>我是新闻页</h2>   
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h2>我是关于我们</h2>   
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <h2>登录页</h2>   
          <button @click="doLogin">点击登录</button>
        </div>
      `,
      methods: {
        doLogin(){
          setTimeout(() =>{
            const token = 'dwdwegrhtyu';
            // 缓存
            localStorage.setItem('token', token);
            // 跳转到首页
            if(this.$route.query.from){
              this.$router.replace(this.$route.query.from)
            }else{
              this.$router.replace('/home')
            }
          }, 1000)
        }
      }
    }
    // 路由规则
    const routes = [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home,
        meta: {
          needLogin: false
        }
      },
      {
        path: '/news',
        component: News,
        meta: {
          needLogin: false
        }
      },
      {
        path: '/about',
        component: About,
        meta: {
          needLogin: true
        },
        beforeEnter: (to, from, next) => {
          const token = localStorage.getItem('token');
          if(token){
            // 登录了
            next()
          }else{
            next({
              path: '/login',
              query: {
                from: '/about'
              }
            })
          }
        }
      },
      {
        path: '/login',
        component: Login,
        meta: {
          needLogin: false
        }
      }
    ]
    // 创建路由对象
    const router = new VueRouter({

      routes // 代表路由规则 数组
    })
   
    const vm = new Vue({
      el: '#app',
      router
    })
  </script>
</body>

</html>